package org.example.frw.verify;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import lombok.extern.slf4j.Slf4j;
import org.example.frw.exception.InvalidParamException;
import org.hibernate.validator.HibernateValidator;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
public enum ValidateUtil {
    INSTANCE;

    private final Validator validator;

    ValidateUtil() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                .failFast(false)
                .buildValidatorFactory();
        this.validator = validatorFactory.getValidator();
    }

    public <T> void validate(T t) throws InvalidParamException {
        log.info("do validate...");
        if (t == null) {
            throw new InvalidParamException("null param found");
        }

        List<String> errorList = new ArrayList<>();
        Set<ConstraintViolation<T>> constraintViolations = this.validator.validate(t);
        for (ConstraintViolation<T> violation : constraintViolations) {
            String path = violation.getPropertyPath().toString();
            String message = violation.getMessage();
            Object invalidValue = violation.getInvalidValue();
            // 构建详细的错误信息
            String detail = String.format("\nField: %s, Error: %s, Actual Value: %s",
                    path, message, invalidValue);
            errorList.add(detail);
        }
        if (!errorList.isEmpty()) {
            throw new InvalidParamException(String.join(";", errorList));
        }
    }
}